package util

import (
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"go-proxy/common"
	"time"
)

func CreatToken(username string, tokenExpire int64, secret string) (string, error) {
	claims := jwt.MapClaims{
		common.USERNAME: username,
		common.EXPIRE:   time.Now().Add(time.Second * time.Duration(tokenExpire)).Unix(),
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	tokenStr, err := token.SignedString([]byte(secret))
	return tokenStr, err
}

func ValidateToken(tokenString string, secret string) (*jwt.Token, error) {
	// 解析 JWT
	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		// 验证签名算法是否正确
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
		}

		// 设置密钥
		return []byte(secret), nil
	})

	if err != nil {
		return nil, err
	}

	// 检查是否已过期
	if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
		expirationTime := claims[common.EXPIRE].(float64)
		if time.Now().Unix() > int64(expirationTime) {
			return nil, fmt.Errorf("token has expired")
		}
		return token, nil
	}

	return nil, fmt.Errorf("invalid token")
}
